﻿/// <reference path="jquery-1.5.1-vsdoc.js" />

$(document).ready(
    function () {
        loadStates();

        $("#States").change(loadSuburbs);
        $('#Suburbs').change(setSuburbId);
    }
);



function loadStates() {
    
    var states = $('#States');

    $.ajax({
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json; charset=utf-8;',
        url: '/Address/States',
        success: function (result) {

            states.find('option').remove();
            states.append("<option> - Select State - </option>");
            $(result).each(function () { $("<option value=" + this.Id + ">" + this.Description + "</option>").appendTo(states); });

            var stateId = $('#Address_Suburb_State_Id').val();
            states.val(stateId);
            loadSuburbs();
        }
    });
          
}


function loadSuburbs() {
       
    var suburbs = $('#Suburbs');
    var states = $("#States");
    suburbs.find('option').remove();
    suburbs.append("<option> - Loading - </option>");

    $.ajax({
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json; charset=utf-8;',
        url: '/Address/Suburbs',
        data: "{'stateId':'" + states.val() + "'}",
        success: function (result) {

            suburbs.find('option').remove();


            if ($(result).size() > 0) { //If a valid state has been selected
                //populate the suburb combobox with the state's suburbs
                suburbs.append("<option> - Select Suburb - </option>");
                $(result).each(function () { $("<option value=" + this.Id + ">" + this.Locality + "</option>").appendTo(suburbs); });
                setSuburb();
         
            }
            else { //If - Select State - is selected
                suburbs.append("<option> - State Selection Required - </option>");
                $('#Address_SuburbId').val("");
                $('#Address_Suburb_State_Id').val("");
            }
        }
    });
}

function setSuburb() {

    //Attempt to set the selected suburb from the suburbId
    var suburbId = $('#Address_SuburbId').val();
    
    //Check to see if the selected Id is in the combo 
    var inCombo = false;
    $("#Suburbs option").each(function () {
        if ($(this).val() == suburbId) { inCombo = true;}
    });
    //If the id is a value in the combo set the suburb
    if (inCombo) {
        $('#Suburbs').val(suburbId);
    }
}
//Sets the value of the Address's Suburb Id to the selected suburb
function setSuburbId() {
    var suburbId = $('#Suburbs').val();
    $('#Address_SuburbId').val(suburbId);
    var stateId = $('#States').val();
    $('#Address_Suburb_State_Id').val(stateId);    
}